/**
 * WebSocket工具类
 * 用于处理聊天WebSocket连接和消息
 */
class WebSocketManager {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000;
        this.heartbeatInterval = null;
        this.messageHandlers = new Map();
        this.baseUrl = 'ws://localhost:8080/api'; // 需要根据实际情况修改
        this.isConnecting = false; // 是否正在连接中
    }

    /**
     * 连接WebSocket
     */
    connect() {
        return new Promise((resolve, reject) => {
            try {
                if (this.isConnected || this.isConnecting) {
                    console.log('WebSocket已连接或正在连接中');
                    resolve();
                    return;
                }

                const token = uni.getStorageSync('token');
                if (!token) {
                    reject(new Error('未找到登录token'));
                    return;
                }

                this.isConnecting = true;
                const wsUrl = `${this.baseUrl}/ws/chat?token=${token}`;
                console.log('正在连接WebSocket:', wsUrl);

                this.ws = uni.connectSocket({
                    url: wsUrl, complete: () => {
                    }
                });

                this.ws.onOpen(() => {
                    console.log('WebSocket连接成功');
                    this.isConnected = true;
                    this.isConnecting = false;
                    this.reconnectAttempts = 0;
                    this.startHeartbeat();
                    resolve();
                });

                this.ws.onMessage((res) => {
                    console.log('收到WebSocket消息:', res.data);
                    try {
                        this.handleMessage(res.data);
                    } catch (error) {
                        console.error('处理WebSocket消息时出错:', error);
                    }
                });

                this.ws.onClose(() => {
                    console.log('WebSocket连接关闭');
                    this.isConnected = false;
                    this.stopHeartbeat();
                    this.attemptReconnect();
                });

                this.ws.onError((error) => {
                    console.error('WebSocket连接错误:', error);
                    this.isConnected = false;
                    this.isConnecting = false;
                    reject(error);
                });

            } catch (error) {
                console.error('创建WebSocket连接失败:', error);
                this.isConnecting = false;
                reject(error);
            }
        });
    }

    /**
     * 断开连接
     */
    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.isConnected = false;
        this.stopHeartbeat();
        this.reconnectAttempts = this.maxReconnectAttempts; // 阻止重连
    }

    /**
     * 发送消息
     */
    sendMessage(message) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket未连接，无法发送消息');
            return false;
        }

        try {
            this.ws.send({
                data: JSON.stringify(message)
            });
            return true;
        } catch (error) {
            console.error('发送消息失败:', error);
            return false;
        }
    }

    /**
     * 处理接收到的消息
     */
    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log('收到WebSocket消息:', message.type);

            // 根据消息类型调用相应的处理器
            const handler = this.messageHandlers.get(message.type);
            if (handler) {
                handler(message);
            }

            // 触发全局事件
            uni.$emit('websocket-message', message);

        } catch (error) {
            console.error('处理WebSocket消息失败:', error);
        }
    }

    /**
     * 注册消息处理器
     */
    onMessage(type, handler) {
        this.messageHandlers.set(type, handler);
    }

    /**
     * 移除消息处理器
     */
    offMessage(type) {
        this.messageHandlers.delete(type);
    }

    /**
     * 发送聊天消息
     */
    sendChatMessage(receiverId, messageType, content, mediaUrl = null) {
        const message = {
            type: 'SEND_MESSAGE', receiverId: receiverId, messageType: messageType, content: content, mediaUrl: mediaUrl
        };
        return this.sendMessage(message);
    }

    /**
     * 标记消息为已读
     */
    markAsRead(sessionId) {
        const message = {
            type: 'MARK_READ', sessionId: sessionId
        };
        return this.sendMessage(message);
    }

    /**
     * 开始心跳
     */
    startHeartbeat() {
        this.heartbeatInterval = setInterval(() => {
            if (this.isConnected) {
                this.sendMessage({
                    type: 'HEARTBEAT'
                });
            }
        }, 30000); // 30秒发送一次心跳
    }

    /**
     * 停止心跳
     */
    stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval);
            this.heartbeatInterval = null;
        }
    }

    /**
     * 尝试重连
     */
    attemptReconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            console.log('达到最大重连次数，停止重连');
            return;
        }

        this.reconnectAttempts++;
        console.log(`尝试第${this.reconnectAttempts}次重连...`);

        setTimeout(() => {
            this.connect().catch(error => {
                console.error('重连失败:', error);
            });
        }, this.reconnectInterval);
    }

    /**
     * 获取连接状态
     */
    getConnectionState() {
        return {
            isConnected: this.isConnected, reconnectAttempts: this.reconnectAttempts
        };
    }
}

// 创建全局实例
const websocketManager = new WebSocketManager();

export default websocketManager;
